package org.lijma.demo.siteplan.config.impl;

import org.lijma.demo.siteplan.config.LoadFailedException;
import org.lijma.demo.siteplan.config.RouteInfo;
import org.lijma.demo.siteplan.config.RoutesLoader;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileRoutesLoader implements RoutesLoader {

    private static Logger LOG = Logger.getLogger(FileRoutesLoader.class.getName());

    private static final String TESTED_ROUTES="AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7";
//  private static final String CONFIG_FILE_NAME="route.info";
//  private String filePath;

    private Reader reader;
    private List<RouteInfo> routes;

    public FileRoutesLoader(){
        try {
//          filePath = FileRoutesLoader.class.getResource("/"+CONFIG_FILE_NAME).getFile();
//          reader = new FileReader(new File(filePath));
            reader = new StringReader(TESTED_ROUTES);
            routes = new ArrayList<RouteInfo>();
        } catch (Exception e) {
            LOG.log(Level.SEVERE,"Stop configuratio file ["+TESTED_ROUTES+"] cannot be found!");
        }
    }

    public List<RouteInfo> loadRouteInfo() throws LoadFailedException {
        BufferedReader bufferedReader = new BufferedReader(reader);
        List<RouteInfo> routeInfos= null;
        String line;
        try {
            if ((line = bufferedReader.readLine()) != null){
                routeInfos = new ArrayList<RouteInfo>();

                String[] items = line.split(",");
                for (String item: items ) {
                    item = item.trim();
                    RouteInfo ri = new RouteInfo();
                    ri.setStartStopName(item.charAt(0)+"");
                    ri.setEndStopName(item.charAt(1)+"");
                    int weight = Integer.parseInt(item.charAt(2)+"");
                    if(weight <= 0){
                        throw new Exception("weight cannot be negative or zero number");
                    }
                    ri.setWeight(weight);
                    routeInfos.add(ri);
                }
            }
        }catch (Exception e) {
            LOG.severe("read route file failed, route file not exist or wrong format: "+e);
            close();
            throw new LoadFailedException("read route file failed, route file not exist or wrong format",e);
        }
        close();
        return routeInfos;
    }

    public void setReader(Reader reader) {
        this.reader = reader;
    }

    private void close(){
        try {
            reader.close();
        } catch (IOException e1) {
            LOG.severe("close reader failed: "+e1);
        }
    }

}
